/**
 * Copyright 1999-2015 dangdang.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package spring.cloud.tasks.api.zookeeper.impl;

import com.google.common.base.Strings;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import spring.cloud.tasks.api.utils.ThreadLocalCuratorClient;
import spring.cloud.tasks.api.zookeeper.ZooKeeper;
import spring.cloud.tasks.api.zookeeper.ZooKeeperRepository;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class CuratorRepositoryImpl implements ZooKeeperRepository {

    private static final int WAITING_SECONDS = 2;
    /**
     * 会话超时时间
     */
    private static final int SESSION_TIMEOUT = 20 * 1000;
    /**
     * 连接超时时间
     */
    private static final int CONNECTION_TIMEOUT = 20 * 1000;
    protected static Logger log = LoggerFactory.getLogger(CuratorRepositoryImpl.class);

    @Override
    public CuratorFramework connect(final String connectString, final String namespace, final String digest) {
        Builder builder = CuratorFrameworkFactory.builder()//
                .connectString(connectString)//
                .connectionTimeoutMs(CONNECTION_TIMEOUT)//
                .sessionTimeoutMs(SESSION_TIMEOUT)//
                .retryPolicy(new ExponentialBackoffRetry(1000, 3, 3000));
        if (namespace != null) {
            builder.namespace(namespace);
        }
        if (!Strings.isNullOrEmpty(digest)) {
            builder.authorization("digest", digest.getBytes(StandardCharsets.UTF_8)).aclProvider(new ACLProvider() {

                @Override
                public List<ACL> getDefaultAcl() {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }

                @Override
                public List<ACL> getAclForPath(final String path) {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }
            });
        }
        CuratorFramework curatorFramework = builder.build();
        curatorFramework.start();
        boolean established = false;
        try {
            established = curatorFramework.blockUntilConnected(WAITING_SECONDS, TimeUnit.SECONDS);
        } catch (final InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        if (established) {
            return curatorFramework;
        }
        CloseableUtils.closeQuietly(curatorFramework);
        return null;
    }

    @Override
    public ZooKeeper getZooKeeper() {
        return new ZooKeeperImpl(ThreadLocalCuratorClient.getCuratorFrameworkThreadLocal());
    }

    @Override
    public ZooKeeper getZooKeeper(CuratorFramework curatorFramework) {
        return new ZooKeeperImpl(curatorFramework);
    }

}
